﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

namespace SmartSiteManagementSystem.AppApi.Filter
{
    /// <summary>
    /// https://www.cnblogs.com/hnsongbiao/p/7039666.html
    /// https://www.cnblogs.com/chinaliu/p/11532492.html
    /// </summary>
    public class ApiControllerActionFilter:ActionFilterAttribute
    {
        private SortedDictionary<string, object> _data;
        private Stopwatch _stopwatch;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {

            try
            {
                _stopwatch.Restart();
                var descriptor = (ControllerActionDescriptor)context.ActionDescriptor;
                //获取控制器名称
                var controllerName = descriptor.ControllerName;
                //获取action名称
                var actionName = descriptor.ActionName;
                _data = new SortedDictionary<string, object>();
                HttpRequest request = context.HttpContext.Request;
                _data.Add("request.url", request.Path.ToString());
                _data.Add("request.headers", request.Headers.ToDictionary(x => x.Key, v => string.Join(";", v.Value.ToList())));
                _data.Add("request.method", request.Method);
                _data.Add("request.executeStartTime", DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                base.OnActionExecuting(context);
            }
            catch(Exception e)
            {

            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
        }


        /// <summary>
        /// 读取request 的提交内容
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        /// <returns></returns>
        public string GetRequestValues(ActionExecutedContext actionExecutedContext)
        {
           //获取body内容
            var reader = new StreamReader(actionExecutedContext.HttpContext.Request.Body);
            var contentFromBody = reader.ReadToEnd();
            return contentFromBody;
        }


    }

}

